package com.shyroke.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DBUtil {
	private static final String DRIVER = "com.mysql.jdbc.Driver";
	private static final String USER = "root";
	private static final String PASSWD = "";
	private static final String URL = "jdbc:mysql://127.0.0.1:3306/shiro?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
	private static ComboPooledDataSource dataSource = null;
	static {
		try {
			Class.forName(DRIVER);

			Context context = new InitialContext();

			dataSource = new ComboPooledDataSource();
			dataSource.setMaxPoolSize(50);
			dataSource.setInitialPoolSize(20);
			dataSource.setJdbcUrl(URL);
			dataSource.setDriverClass(DRIVER);
			dataSource.setUser(USER);
			dataSource.setPassword(PASSWD);

		} catch (Exception e) {

			throw new RuntimeException("驱动包加载故障");
		}

	}

	public static Connection getConn() {
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return conn;
	}
	
	public static void  close(Connection con,PreparedStatement ps,ResultSet rs)throws Exception{
		if(con!=null){
			con.close();
		}
		if(ps!=null){
			ps.close();
		}
		if(rs!=null){
			rs.close();
		}
	}
	

	public static void main(String[] args) {
		for (int i = 0; i < 100; i++) {

			System.out.println(DBUtil.getConn() + "\t " + i);
		}
	}
}
